<template>
    <van-nav-bar title="收货地址" left-text="" left-arrow @click-left="goBack" />

    <!-- 确认地址 -->
    <van-address-list v-if="action" v-model="chosenId" :list="addresslist" default-tag-text="默认" @add="onAdd" @edit="onEdit" @select="chooseed"/>

    <!-- 收货地址 -->
    <van-address-list v-else v-model="chosenId" :list="addresslist" default-tag-text="默认" @add="onAdd" @edit="onEdit" @select="selected"/>
</template>
<script setup>
const { proxy } = getCurrentInstance()
const goBack = () => { proxy.$router.go(-1) }
const LoginUser = reactive(proxy.$cookies.get('LoginUser') ? proxy.$cookies.get('LoginUser') : {})
const chosenId = ref('1');
const addresslist = ref([])
const action = ref(proxy.$route.query.action ? proxy.$route.query.action: '')
onBeforeMount(() =>{
    getAddressData()
})
const getAddressData = async() =>{
    let result = await Api.addressIndex({busid: LoginUser.id})
    if(result.code == 1)
    {
        addresslist.value = [];
        result.data.forEach((item) =>{
            addresslist.value.push({
                id: item.id,
                name: item.consignee,
                tel: item.mobile,
                address: item.region_text + item.address,
                isDefault: item.status == '1' ? true : false
            })

            if(item.status == '1')
            {
                chosenId.value = item.id
            }
        })

    }
}

const onAdd = () =>{
    proxy.$router.push('/business/address/add')
}
const onEdit = (val) =>{
    proxy.$router.push({
        path: '/business/address/edit',
        query: {
            addressid: val.id
        }
    })
}

// 切换默认地址
const selected = async(val) =>{
    let result = await Api.addressCheck({busid: LoginUser.id, addressid: val.id})
    if(result.code == 1)
    {
        getAddressData()
    }
    else
    {
        error(result.msg);
    }
}

// 选择收货地址
const chooseed = (val) =>{
    proxy.$cookies.set('address', {
        id: val.id,
        mobile: val.tel,
        consignee: val.name,
        province: val.province,
        city: val.city,
        district: val.district,
        address: val.address
    })
    goBack();
}
</script>